package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.Combo;
import com.ruoyi.merchant.domain.ComboProduct;
import com.ruoyi.merchant.domain.Product;
import com.ruoyi.merchant.domain.dto.ComboProductDTO;
import com.ruoyi.merchant.domain.dto.ComboSubmitDTO;
import com.ruoyi.merchant.mapper.ComboMapper;
import com.ruoyi.merchant.mapper.ComboProductMapper;
import com.ruoyi.merchant.mapper.ProductMapper;
import com.ruoyi.merchant.service.IComboService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 套餐Service业务层处理
 */
@Service
public class ComboServiceImpl implements IComboService {

    @Autowired
    private ComboMapper comboMapper;

    @Autowired
    private ComboProductMapper comboProductMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Combo selectComboByComboId(Long comboId) {
        Combo combo = comboMapper.selectComboByComboId(comboId);
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (combo != null && !merchantId.equals(combo.getMerchantId())) {
            throw new ServiceException("无权访问该套餐");
        }

        // 加载套餐商品列表
        if (combo != null) {
            List<ComboProduct> products = comboProductMapper.selectByComboId(comboId);
            combo.setProducts(products);
        }

        return combo;
    }

    @Override
    public List<Combo> selectComboList(Combo combo) {
        combo.setMerchantId(MerchantSecurityUtils.getMerchantId());
        return comboMapper.selectComboList(combo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCombo(ComboSubmitDTO comboSubmitDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 1. 验证所有商品是否存在且已审核通过
        for (ComboProductDTO productDTO : comboSubmitDTO.getProducts()) {
            Product product = productMapper.selectProductByProductId(productDTO.getProductId());
            if (product == null) {
                throw new ServiceException("商品不存在：" + productDTO.getProductId());
            }
            if (!merchantId.equals(product.getMerchantId())) {
                throw new ServiceException("无权使用该商品：" + product.getName());
            }
            if (product.getAuditStatus() != 1) {
                throw new ServiceException("商品未通过审核，不能添加到套餐：" + product.getName());
            }
        }

        // 2. 创建套餐
        Combo combo = new Combo();
        combo.setMerchantId(merchantId);
        combo.setName(comboSubmitDTO.getName());
        combo.setDescription(comboSubmitDTO.getDescription());
        combo.setImageUrl(comboSubmitDTO.getImageUrl());
        combo.setMarketPrice(comboSubmitDTO.getMarketPrice());
        combo.setRegionPrice(comboSubmitDTO.getRegionPrice());
        combo.setStatus(0); // 默认下架
        combo.setSortOrder(comboSubmitDTO.getSortOrder() != null ? comboSubmitDTO.getSortOrder() : 0);

        int result = comboMapper.insertCombo(combo);
        if (result <= 0) {
            throw new ServiceException("创建套餐失败");
        }

        Long comboId = combo.getComboId();

        // 3. 添加套餐商品
        List<ComboProduct> comboProducts = new ArrayList<>();
        for (int i = 0; i < comboSubmitDTO.getProducts().size(); i++) {
            ComboProductDTO productDTO = comboSubmitDTO.getProducts().get(i);
            ComboProduct comboProduct = new ComboProduct();
            comboProduct.setComboId(comboId);
            comboProduct.setProductId(productDTO.getProductId());
            comboProduct.setQuantity(productDTO.getQuantity());
            comboProduct.setSortOrder(productDTO.getSortOrder() != null ? productDTO.getSortOrder() : i);
            comboProducts.add(comboProduct);
        }

        if (!comboProducts.isEmpty()) {
            comboProductMapper.batchInsert(comboProducts);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateCombo(ComboSubmitDTO comboSubmitDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long comboId = comboSubmitDTO.getComboId();

        if (comboId == null) {
            throw new ServiceException("套餐ID不能为空");
        }

        // 1. 验证套餐是否存在且属于当前商家
        Combo existCombo = comboMapper.selectComboByComboId(comboId);
        if (existCombo == null) {
            throw new ServiceException("套餐不存在");
        }
        if (!merchantId.equals(existCombo.getMerchantId())) {
            throw new ServiceException("无权修改该套餐");
        }

        // 2. 验证所有商品是否存在且已审核通过
        for (ComboProductDTO productDTO : comboSubmitDTO.getProducts()) {
            Product product = productMapper.selectProductByProductId(productDTO.getProductId());
            if (product == null) {
                throw new ServiceException("商品不存在：" + productDTO.getProductId());
            }
            if (!merchantId.equals(product.getMerchantId())) {
                throw new ServiceException("无权使用该商品：" + product.getName());
            }
            if (product.getAuditStatus() != 1) {
                throw new ServiceException("商品未通过审核，不能添加到套餐：" + product.getName());
            }
        }

        // 3. 更新套餐基本信息
        Combo combo = new Combo();
        combo.setComboId(comboId);
        combo.setMerchantId(merchantId);
        combo.setName(comboSubmitDTO.getName());
        combo.setDescription(comboSubmitDTO.getDescription());
        combo.setImageUrl(comboSubmitDTO.getImageUrl());
        combo.setMarketPrice(comboSubmitDTO.getMarketPrice());
        combo.setRegionPrice(comboSubmitDTO.getRegionPrice());
        combo.setSortOrder(comboSubmitDTO.getSortOrder());

        int result = comboMapper.updateCombo(combo);

        // 🔥🔥🔥 4. 物理删除套餐的所有商品（简单有效）
        comboProductMapper.deleteByComboId(comboId);

        // 5. 添加新的套餐商品
        List<ComboProduct> comboProducts = new ArrayList<>();
        for (int i = 0; i < comboSubmitDTO.getProducts().size(); i++) {
            ComboProductDTO productDTO = comboSubmitDTO.getProducts().get(i);
            ComboProduct comboProduct = new ComboProduct();
            comboProduct.setComboId(comboId);
            comboProduct.setProductId(productDTO.getProductId());
            comboProduct.setQuantity(productDTO.getQuantity());
            comboProduct.setSortOrder(productDTO.getSortOrder() != null ? productDTO.getSortOrder() : i);
            comboProducts.add(comboProduct);
        }

        if (!comboProducts.isEmpty()) {
            comboProductMapper.batchInsert(comboProducts);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteComboByComboIds(Long[] comboIds) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        for (Long comboId : comboIds) {
            Combo combo = comboMapper.selectComboByComboId(comboId);
            if (combo == null || !merchantId.equals(combo.getMerchantId())) {
                throw new ServiceException("包含无权删除的套餐");
            }

            // 物理删除套餐商品
            comboProductMapper.deleteByComboId(comboId);
        }
        return comboMapper.deleteComboByComboIds(comboIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteComboByComboId(Long comboId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Combo combo = comboMapper.selectComboByComboId(comboId);
        if (combo == null || !merchantId.equals(combo.getMerchantId())) {
            throw new ServiceException("无权删除该套餐");
        }

        // 物理删除套餐商品
        comboProductMapper.deleteByComboId(comboId);

        return comboMapper.deleteComboByComboId(comboId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateComboStatus(Long[] comboIds, Integer status) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 验证所有套餐是否属于当前商家
        for (Long comboId : comboIds) {
            Combo combo = comboMapper.selectComboByComboId(comboId);
            if (combo == null || !merchantId.equals(combo.getMerchantId())) {
                throw new ServiceException("包含无权操作的套餐");
            }
        }

        return comboMapper.updateComboStatus(comboIds, status, merchantId);
    }

    @Override
    public Map<String, Object> countComboByStatus() {
        return comboMapper.countComboByStatus(MerchantSecurityUtils.getMerchantId());
    }
}
